package com.rxw.nutmall.exception;

import com.rxw.nutmall.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestControllerAdvice(annotations = {RestController.class, Controller.class})
public class ExceptionControllerAdvice {
    @ExceptionHandler(value = {MethodArgumentNotValidException.class})
    public Result<Object> handleValidException(MethodArgumentNotValidException e) {
        Map<String, String> errorMap = new HashMap<>();
        BindingResult result = e.getBindingResult();
        result.getFieldErrors().forEach((fieldError) -> errorMap.put(fieldError.getField(), fieldError.getDefaultMessage()));
        return Result.error(ErrorCode.DATA_SCOPE_PARAMS_ERROR,"数据校验异常", errorMap);
    }
}
